﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StarsAdmin.Application.Dict.Dtos;
using StarsAdmin.Application.File.Dtos;
using StarsAdmin.Core.Cache;
using StarsAdmin.Core.Consts;
using StarsAdmin.Core.DB.Entities;
using StarsAdmin.Core.Exceptions;
using StarsAdmin.Core.Extensions;
using StarsAdmin.Core.Models;
using StarsAdmin.Repository.Address;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarsAdmin.Application.Dict.Services
{
    public class DictTypeService : IDictTypeService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly IDictTypeRepository _dictTypeRepository;

        public DictTypeService(IMapper mapper, ICacheService cacheService, IDictTypeRepository dictTypeRepository)
        {
            _mapper = mapper;
            _cache = cacheService;
            _dictTypeRepository = dictTypeRepository;
        }

        public async Task<List<DictTypeDto>> GetAllAsync(BaseQueryInput input)
        {
            var result = await _dictTypeRepository.GetAll().AsNoTracking()
                  .WhereIf(input != null && input.QueryConditions.Any(), input.QueryConditions)
                  .OrderByIf(input != null && input.Sort != null, input.Sort, input.Order != false)
                  .Include(e => e.Dicts)
                  .ToListAsync();
            return _mapper.Map<List<DictTypeDto>>(result);
        }

        public async Task<Page<DictTypeDto>> GetPageAsync(PageQueryInput input)
        {
            var result = await _dictTypeRepository.GetAll().AsNoTracking()
                      .WhereIf(input != null && input.QueryConditions.Any(), input.QueryConditions)
                      .OrderByIf(input != null && input.Sort != null, input.Sort, input.Order != false)
                      .Include(e => e.Dicts)
                      .ToPageListAsync(input.CurrentPage, input.PageSize);
            return _mapper.Map<Page<DictTypeDto>>(result);
        }

        public async Task<DictTypeDto?> GetByIdAsync(long id)
        {
            var result = await _dictTypeRepository.GetById(id).Include(e => e.Dicts).FirstOrDefaultAsync();
            return _mapper.Map<DictTypeDto>(result);
        }

        public async Task<List<DictTypeDto>> GetByIdsAsync(long[] ids)
        {
            var result = await _dictTypeRepository.GetByIds(ids).Include(e => e.Dicts).ToListAsync();
            return _mapper.Map<List<DictTypeDto>>(result);
        }

        public async Task<FileContentResult?> ExportAsync(long[] ids)
        {
            var export = await _dictTypeRepository.GetByIds(ids).ToListAsync();
            return await _mapper.Map<List<ExportDictTypeDto>>(export).ToExcelAsync("字典类型");
        }

        public async Task<bool> AddAsync(AddDictTypeInput input)
        {
            var entity = _mapper.Map<DictTypeEntity>(input);
            var result = await _dictTypeRepository.AddAndSaveAsync(entity);
            if (result)
            {
                await _cache.RemoveAsync(CacheKeyConst.DictTypeCacheKey);
            }
            return result;
        }

        public async Task<bool> UpdateAsync(UpdateDictTypeInput input)
        {
            var dictType = await _dictTypeRepository.GetByIdAsync(input.Id);
            if (dictType == null)
            {
                throw new NotFoundException("未找到指定的字典类型数据。");
            }
            var entity = _mapper.Map(input, dictType);
            var result = await _dictTypeRepository.UpdateAndSaveAsync(entity);
            if (result)
            {
                await _cache.RemoveAsync(CacheKeyConst.DictTypeCacheKey);
            }
            return result;
        }

        public async Task<bool> DeleteAsync(long id)
        {
            var entity = await _dictTypeRepository.GetByIdAsync(id);
            if (entity == null)
            {
                throw new NotFoundException("未找到指定的字典类型数据。");
            }
            var result = await _dictTypeRepository.DeleteAndSaveAsync(entity.Id);
            if (result)
            {
                await _cache.RemoveAsync(CacheKeyConst.DictTypeCacheKey);
            }
            return result;
        }

        public async Task<bool> BatchDeleteAsync(long[] ids)
        {
            var entities = await _dictTypeRepository.GetByIdsAsync(ids);
            if (entities == null || entities.Count() < 1)
            {
                throw new NotFoundException("未找到指定的字典数据。");
            }
            var result = await _dictTypeRepository.DeleteRangeAndSaveAsync(ids);
            if (result)
            {
                await _cache.RemoveAsync(CacheKeyConst.DictTypeCacheKey);
            }
            return result;
        }
    }
}